package com.admin.education.common.dml;

import com.admin.education.config.DMLPOJOAnnotation;
import com.admin.education.models.UpdateLog;
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.inject.Provider;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import java.lang.reflect.Method;
import java.util.List;

@Aspect
@Component
public class DMLAspect {
    @Autowired
    private Provider<EntityManager> em;

    @Pointcut("@annotation(com.admin.education.config.DMLPOJOAnnotation)")
    public void annotationPointCut() {
    }

    @After("annotationPointCut()")
    @Transactional
    public void after(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Object[] objects =  joinPoint.getArgs();
        DMLPOJOAnnotation dmlpojoAnnotation = method.getAnnotation(DMLPOJOAnnotation.class);

        for (Object object : objects) {
            if(null==object)
                continue;
            if(object instanceof List){
                List entities = (List)object;
                for (Object entity : entities) {
                    UpdateLog updateLog = new UpdateLog();
                    updateLog.setAction(dmlpojoAnnotation.action());
                    updateLog.setContent(JSON.toJSONString(entity));
                    updateLog.setName(entity.getClass().getName());

                    em.get().persist(updateLog);
                }
            }
            else{
                UpdateLog updateLog = new UpdateLog();
                updateLog.setAction(dmlpojoAnnotation.action());
                updateLog.setContent(JSON.toJSONString(object));
                updateLog.setName(object.getClass().getName());

                em.get().persist(updateLog);
            }
        }
    }
}
